package com.relax.mybatis.encrypt.interceptor;

import java.util.Properties;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;

import com.relax.mybatis.encrypt.config.EncryptProperties;
import com.relax.mybatis.encrypt.util.EncryptUtil;

/**
 * @author relax
 * @date 2022/07/05
 * @desc 加密拦截器
 */
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class EncryptInterceptor implements Interceptor {

    private EncryptProperties encryptProperties;

    public EncryptInterceptor(EncryptProperties encryptProperties) {
        this.encryptProperties = encryptProperties;
    }

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        return EncryptUtil.handleExecutor(invocation, (metaObject, fieldSetProperty) -> EncryptUtil
                .doEecrypt(this.encryptProperties, metaObject, fieldSetProperty));
    }

    public Object plugin(Object o) {
        return (o instanceof Executor) ? Plugin.wrap(o, this) : o;
    }

    public void setProperties(Properties paramProperties) {
        // do nothing
    }
}
